//
// Created by denglibin on 2019/6/21 0021.
//
/**单向链表实现**/
#include <stdio.h>
#include <stdlib.h>

/**
 * 单链表节点
 */
typedef struct single_list_node
{
    int data;
    struct single_list_node *next;
} SingleListNode;

/**
 * 单链表
 */
typedef struct single_linked_list
{
    int size;             //大小
    SingleListNode *head; //头节点
    SingleListNode *tail; //尾节点
} SingleLinkedList;

/**
 * 创建一个节点
 * @param data
 * @return
 */
static SingleListNode *createNode(int data)
{
    SingleListNode *node = (SingleListNode *)calloc(1, sizeof(SingleListNode));
    if (node == NULL)
    {
        printf("calloc error\n");
        exit(-1);
    }
    node->data = data;
    node->next = NULL;
    return node;
}

/**
 * 创建一个链表
 * @param limit 链表大小
 * @return
 */
SingleLinkedList *createLinkedList()
{
    SingleLinkedList *list = (SingleLinkedList *)calloc(1, sizeof(SingleLinkedList));
    if (list == NULL)
    {
        printf("calloc error\n");
        exit(-1);
    }
    list->size = 0;
    list->head = NULL;
    list->tail = NULL;
    return list;
}

/**
 * 添加元素
 * @param node
 */
static void addNode(SingleLinkedList *list, int data)
{
    SingleListNode *node = createNode(data);
    if (list->size == 0)
    {
        list->head = node;
        list->tail = node;
    }
    else
    {
        list->tail->next = node;
        list->tail = node;
    }
    list->size++;
}
/**
 * 查找
 * @param index 位置
 * @return
 */
static int get(SingleLinkedList *list, int index)
{
    if (index < 0)
    {
        printf("index error");
        return -1;
    }
    SingleListNode *tempNode = list->head;
    while (index)
    {
        tempNode = tempNode->next;
        index--;
    }
    return tempNode->data;
}

/**
 * 清空
 * @param list
 */
static void clear(SingleLinkedList *list)
{
    SingleListNode *tempNode = list->head;
    SingleListNode *nextNode;
    while (tempNode != NULL)
    {
        nextNode = tempNode->next;
        free(tempNode);
        tempNode = nextNode;
    }
    list->size = 0;
    list->head = NULL;
    list->tail = NULL;
}

/**
 * 打印元素
 * @param list
 */
static void show(SingleLinkedList *list)
{
    SingleListNode *tempNode = list->head;
    while (tempNode != NULL)
    {
        printf("%d\n", tempNode->data);
        tempNode = tempNode->next;
    }
}

int main20()
{
    SingleLinkedList *list = createLinkedList();
    for (int i = 0; i < 100; i++)
    {
        addNode(list, i);
    }
    show(list);
    printf("-->%d\n", get(list, 50));
    clear(list);
    free(list);
    return 0;
}